{% load i18n %}
{% extends "index.html" %}

{% block stylesheet %}{{ base_url }}/css/sms/extension.css{% endblock %}

{% block content %}
<script type="text/javascript">

/* Extend jQuery with functions for PUT and DELETE requests. */

function _ajax_request(url, data, callback, type, method){
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
}

jQuery.extend({
    put: function(url, data, callback, type){
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type){
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

function select_user(user) {
	$("#destination").hide();
	$("#destination").text(user.childNodes[1].textContent);
	$("#destination").show("slow");
}

function add_new_user_waiting() {
    var user = $("#user-to-add").val();    
    var url = "{{ base_url }}/sms/user/" + user + "/";
    	
    $.put(url, '', function(json){
        var message = $('<div id="dialog">' + json.message + '</div>');
	message.hide();
	message.dialog({
	     title: "Adding user",
	     buttons: {
	        Close: function(){
	           $(this).dialog('destroy');
                }
             },
	     modal: "true"
        });
        message.fadeIn("slow");
    }, 'json');
}


function delete_user_allowed(li){
    var user = li.childNodes[0].data;
    var url = "{{ base_url }}/sms/user/" + user + "/";
    
    var message = $('<div id="dialog"> Are you sure you want to delete <b>' + user + '</b> from your list of users allowed?</div>');
    message.hide();
    message.dialog({
        title: "Confirmation",
        buttons: {
            No: function(){
                $(this).dialog('destroy');
            },
            Yes: function(){
                $.delete_(url, '', function(json){
                    $(li).css('background', 'red').fadeOut("slow");
			  $("#destination").hide("slow");
			  $("div:contains(" + json.email + ")", $("#users-table")).css('background', 'red').fadeOut("slow");
                }, 'json');
                $(this).dialog('destroy');
            }
        },
        modal: "true"
    });
    message.fadeIn("slow");
	
}

function decide_user_waiting(li){
    var user = li.childNodes[0].data;
    var url = "{{ base_url }}/sms/user/" + user + "/";
	
    var message = $('<div id="dialog"> Do you want ' + user + ' to be in your list of users allowed?</div>');
    message.hide();
    message.dialog({
	title: "Take a decision",
        buttons: {
            Cancel: function(){
                $(this).dialog('destroy');
            },
            No: function(){
                $.delete_(url, '', function(json){
                    $(li).css('background', 'red').fadeOut("slow");
                }, 'json');
                $(this).dialog('destroy');
            },
            Yes: function(){
                $.post(url, '', function(json){
                    $(li).css('background', 'red').fadeOut("slow");
            	    var newLi1 = '<div id="users-table-entry" onclick="select_user(this)"><div><b>' + json.nick + '</b></div><div><small>' + json.email + '</small></div></div>';
		    $("#users-table").append(newLi1);
		    var newLi2 = '<div id="users-allowed-entry" onclick="delete_user_allowed(this)">' + json.email + '</div>';
		    $("#users-allowed").append(newLi2);
                }, 'json');
                $(this).dialog('destroy');
            }
	},
        modal: "true"
   });
   message.fadeIn("slow");
}

function get_users(){
    var url = "{{ base_url }}/sms/user/";
    var users_a = [];
    var users_w = [];

    $("#users-table-entry").empty;
    $("#users-allowed-entry").empty;
    $("#users-waiting-entry").empty;
    $.getJSON(url, function(json){
        $.each(json.allowed, function(i, item){
            users_a.push(item);
        });
	$.each(json.waiting, function(i, item){
            users_w.push(item);
        });
        users_a = users_a.sort();
        users_w = users_w.sort();
        for (var i = 0; i < users_a.length; i++) {
            var newLi1 = '<div id="users-table-entry" onclick="select_user(this)"><div><b>' + users_a[i].nick + '</b></div><div><small>' + users_a[i].email + '</small></div></div>';
            $("#users-table").append(newLi1);
	    var newLi2 = '<div id="users-allowed-entry" onclick="delete_user_allowed(this)">' + users_a[i].email + '</div>';
	    $("#users-allowed").append(newLi2);
        };
        for (var i = 0; i < users_w.length; i++) {
            var newLi = '<div id="users-waiting-entry" onclick="decide_user_waiting(this)">' + users_w[i] + '</div>';
	    $("#users-waiting").append(newLi);
        };
        $("#users-table").show("slow");
        $("#users-allowed").show("slow");
        $("#users-waiting").show("slow");
    });
}

function update_chunks(textarea) {
	var name = "{{ user.nickname }}";
	var chunks = Math.floor(((name.length + textarea.value.length) / 60) + 1);
	if (chunks >= 4){
		$("#chunks-number").css("background", "red");
		$('#button-sms').attr('disabled', 'disabled');
		$("#button-sms").css("color", "grey");
	}
	else {
		$("#chunks-number").css("background", "green");
		$("#button-sms").css("color", "black");
		$("#button-sms").removeAttr('disabled');		
	}
	$("#chunks-number").text(chunks);
}

function send_sms(){
	var url = "{{ base_url }}/sms/";
	var data = {};
	
	if ($('#destination').text() == '') {
		var message = $('<div id="dialog">Please, pick a destination user</div>');
		message.hide();
		message.dialog({
			title: "Sending sms...",
			buttons: {
				Close: function(){
					$(this).dialog('destroy');
				}
			},
			modal: "true"
		});
		message.fadeIn("slow");
	}
	else {
		data['email'] = $('#destination').text();
		data['message'] = $('#message').val();
		
		$.post(url, data, function(json){
			var message = $('<div id="dialog">' + json.message + '</div>');
			message.hide();
			message.dialog({
				title: "Sending sms...",
				buttons: {
					Close: function(){
						$(this).dialog('destroy');
					}
				},
				modal: "true"
			});
			message.fadeIn("slow");
		}, 'json');
	}
}

$(document).ready(function(){
    get_users();
});

</script>

<div id="extension">

  <div id="mobile">
    <div class="title">
      <h2>Write your SMS</h2>
    </div>
    
    <div id="mobile-users">
      <div class="title">Pick an user from this list:</div>
      <div id="users-table"></div>
    </div>
    
    <div id="mobile-box">
      <div class="title">Send to:</div>
      <div id="destination"></div>
      
      <textarea id="message" name="message" onkeyup="update_chunks(this)"></textarea>
      <input type="submit" value="Send message" id="button-sms" onClick='send_sms();'/><br/>

      <div id="chuncks">
	<div class="title">Number of chunks:</div>
	<div id="chunks-number">
	  0
	</div>
      </div>
    </div>
  </div>


  <div id="users-allowed">
    <div class="title"><h2>Users allowed</h2></div>
  </div>

  <div id="users-waiting">
    <div class="title"><h2>Users waiting</h2></div>
  </div>
  
  <div id="form-new-user">
    <div class="text">
      <div class="title">
	<label for="username"><b>Add new user</b></label>
      </div>
      <input type="text" name="username" id="user-to-add">
      <input type="button" onclick="add_new_user_waiting();" value="Add user"/>
    </div>
  </div>
  
</div>
{% endblock %}
